package org.rcgwt.generators;

import java.io.PrintWriter;

import com.google.gwt.core.ext.BadPropertyValueException;
import com.google.gwt.core.ext.ConfigurationProperty;
import com.google.gwt.core.ext.Generator;
import com.google.gwt.core.ext.GeneratorContext;
import com.google.gwt.core.ext.PropertyOracle;
import com.google.gwt.core.ext.TreeLogger;
import com.google.gwt.core.ext.UnableToCompleteException;
import com.google.gwt.user.rebind.ClassSourceFileComposerFactory;
import com.google.gwt.user.rebind.SourceWriter;

/**
 * The GDATA API Key Generator (To retrieve the API key number from the GWT
 * module configuration file
 * 
 * @author Elian ORIOU
 * 
 */

public class APIKeyGenerator extends Generator {

	private static final String CONFIGURATION_PROPERTY = "org.rcgwt.external.gdata.apikey";
	private String APIKey;

	private static final String PACKAGE = "org.rcgwt.client.ui.calendar.synchronization";
	private static final String NAME = "GoogleAgendaSynchronizerImpl";
	private static final String SUPER_CLASS = "GoogleAgendaSynchronizer";

	@Override
	public String generate(TreeLogger logger, GeneratorContext context,
			String typeName) throws UnableToCompleteException {
		PropertyOracle oracle = context.getPropertyOracle();

		try {
			ConfigurationProperty property = oracle
					.getConfigurationProperty(CONFIGURATION_PROPERTY);
			APIKey = property.getValues().get(0);
		} catch (BadPropertyValueException e) {
			e.printStackTrace();
		}
		ClassSourceFileComposerFactory composer = new ClassSourceFileComposerFactory(
				PACKAGE, NAME);
		PrintWriter pw = context.tryCreate(logger, PACKAGE, NAME);
		composer.setSuperclass(SUPER_CLASS);

		if (pw != null) {
			SourceWriter sw = composer.createSourceWriter(context, pw);

			sw.println("public String getAPIKey() {");
			sw.println("return \"" + APIKey + "\";");
			sw.println("}");

			sw.commit(logger);
		}
		return composer.getCreatedClassName();
	}
}
